package upload

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"hytx_media/pkg/e"
	"hytx_media/pkg/logging"
	"strings"
	"hytx_media/pkg/util"
	"hytx_media/models"
	file2 "hytx_media/pkg/file"
)

func Image(c *gin.Context) map[string]interface{} {

	file, image, err := c.Request.FormFile("image")

	if err != nil {
		logging.Warn(err)
		return map[string]interface{}{
			"code" : http.StatusBadRequest,
			"msg": "image error",
		}
	}

	if image == nil {
		return map[string]interface{}{
			"code": http.StatusBadRequest,
			"msg": "image open failed",
		}
	}

	imageName := GetImageName(image.Filename)
	fullPath := GetImageFullPath()
	//savePath := upload.GetImagePath()
	src := fullPath + imageName

	if !CheckImageExt(imageName) || !CheckImageSize(file) {
		return map[string]interface{}{
			"code": http.StatusInternalServerError,
			"msg": e.GetMsg(e.ERROR_UPLOAD_CHECK_IMAGE_FAIL),
		}
	}

	err = CheckImage(fullPath)
	if err != nil {
		logging.Warn(err)
		return map[string]interface{}{
			"code": http.StatusInternalServerError,
			"msg": e.GetMsg(e.ERROR_UPLOAD_CHECK_IMAGE_FAIL),
		}
	}

	if err := c.SaveUploadedFile(image, src); err != nil {
		logging.Warn(err)
		return map[string]interface{}{
			"code": http.StatusInternalServerError,
			"msg": e.ERROR_UPLOAD_SAVE_IMAGE_FAIL,
		}
	}

	//判断是否登录
	authorization := c.GetHeader("Authorization")
	if authorization != ""{
		sliceToken := strings.Split(authorization, " ")
		token := sliceToken[1]
		if token != ""{
			claims, _ := util.ParseToken(token)
			if claims.Sub != 0 {
				//查询
				row := models.DB.Table("media_user_settings").Select("watermark").Where("media_user_id=?",claims.Sub).Row()
				var isWater bool
				row.Scan(&isWater)
				if isWater {
					row = models.DB.Table("media_user_info").Select("account").Where("media_user_id=?",claims.Sub).Row()
					var text string
					row.Scan(&text)
					imageName =  fullPath + "w-" +imageName
					util.WaterMark(src, imageName, "汇脉宝自媒体平台/"+text)
				}
			}
		}
	}
	size, _ := file2.GetSize(file)
	return map[string]interface{}{
		"code": http.StatusOK,
		"msg": "ok",
		"data": imageName,
		"type": file2.GetExt(imageName),
		"size": size,
	}
}